package com.mandao.concurrency.example.atomic;

import com.mandao.concurrency.annotations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

import static sun.misc.PostVMInitHook.run;

/**
 * 线程安全性:
 *  *   原子性:提供了互斥访问,同一时刻只能有一个线程来对它进行操作
 *
 *  *   AtomicStampedReference: 解决CAS的 ABA问题   解决方案:添加版本号
 * @author 蜗牛
 */
@Slf4j
@ThreadSafe
public class AtomicExample7 {

    private static AtomicStampedReference atomicStampedReference= new AtomicStampedReference(100,0);

    public static void main(String[] args){
        Thread t1 = new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            atomicStampedReference.compareAndSet(100,101,stamp,stamp+1);
            atomicStampedReference.compareAndSet(101,100,stamp,stamp+1);
        });

        Thread t2 = new Thread(()->{
            int stamp = atomicStampedReference.getStamp();
            boolean b = atomicStampedReference.compareAndSet(100, 102, stamp, stamp + 1);
            log.info("atomicStampedReference 通过 stamp 解决CAS ABA问题,{}",b);
        });

        t1.start();
        t2.start();
    }

}
